package org.darcy.service.sys;

import java.io.File;
import java.io.InputStream;

import org.darcy.config.properties.OssClientProperties;
import org.darcy.framework.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 同步到阿里云oss
 */
@Service
@Slf4j
public class OssService {

	@Autowired
	private OssClientProperties clientInfo;

	/**
	 * oss文件上传
	 */
	public void upload(File file) {
		OSS ossClient = new OSSClientBuilder().build(clientInfo.getEndpoint(), clientInfo.getAccessKey(),
				clientInfo.getSecretKey());
		try {
			if (!ossClient.doesBucketExist(clientInfo.getBucketName())) {
				ossClient.createBucket(clientInfo.getBucketName());
			}
			if (!file.exists()) {
				log.error("文件不存在：" + file.getAbsolutePath());
				return;
			}
			PutObjectRequest putObjectRequest = new PutObjectRequest(clientInfo.getBucketName(), file.getPath(), file);
			ossClient.putObject(putObjectRequest);
			// 返回文件访问地址
			String url = "https://" + clientInfo.getBucketName() + "."
					+ clientInfo.getEndpoint().substring(clientInfo.getEndpoint().lastIndexOf("/") + 1) + "/"
					+ file.getPath();
			log.debug("文件上传成功：" + url);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		} finally {
			ossClient.shutdown();
		}
	}

	/**
	 * oss文件上传
	 * 
	 * @param key   oss中的文件名
	 * @param input 浏览器上传的文件流
	 */
	public void upload(String key, InputStream input) {
		OSS ossClient = new OSSClientBuilder().build(clientInfo.getEndpoint(), clientInfo.getAccessKey(),
				clientInfo.getSecretKey());
		try {
			if (!ossClient.doesBucketExist(clientInfo.getBucketName())) {
				ossClient.createBucket(clientInfo.getBucketName());
			}
			if (input == null) {
				log.error("文件流不存在: " + key);
				return;
			}
			PutObjectRequest putObjectRequest = new PutObjectRequest(clientInfo.getBucketName(), key, input);
			ossClient.putObject(putObjectRequest);
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		} finally {
			ossClient.shutdown();
		}
	}
}
